﻿using System;
using System.Net;
using System.Threading;

namespace FlashcardWeb
{
	/// <summary>
	/// This is the manager class that handles running the email operation on a background thread
	/// </summary>
	public class Scheduler : IDisposable
	{
		/// <summary>
		/// Determines the status fo the Scheduler
		/// </summary>        
		public bool Cancelled { get; set; }


		/// <summary>
		/// The frequency of checks against hte POP3 box are 
		/// performed in Seconds.
		/// </summary>
		private int checkFrequency = 180;
		private string pingAddress = string.Empty;

		private AutoResetEvent waitHandle = new AutoResetEvent(false);


		public Scheduler()
		{

		}

		/// <summary>
		/// Starts the background thread processing       
		/// </summary>
		/// <param name="CheckFrequency">Frequency that checks are performed in seconds</param>
		public void Start(int checkFrequency, string pingAddress)
		{
			this.pingAddress = pingAddress;
			this.checkFrequency = checkFrequency;
			this.Cancelled = false;

			Thread t = new Thread(Run);
			t.Start();
		}

		public void Stop()
		{
			this.Cancelled = true;
			this.waitHandle.Set();
		}


		private void Run()
		{

			this.PingServer();

			while (!this.Cancelled)
			{
				// *** Put in 
				this.waitHandle.WaitOne(this.checkFrequency * 1000, true);

			}
		}

		public void PingServer()
		{
			try
			{
				WebClient http = new WebClient();
				http.DownloadString(pingAddress);
			}
			catch 
			{

			}
		}


		public void Dispose()
		{
			this.Stop();
		}
	}
}